package tcp.chat;
//发送类

import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 1.创建tcp协议的socket套接字
 * 2.创建TCP协议的发送类outputStream
 * 3.获取命令行窗口的内容
 * 4.发送信息
 * 5.关闭资源
 */
public class tcp_send extends Thread {
    private Socket socket = null;
    private OutputStream outputStream = null;

    private InetAddress ip = null;
    private int post;
    private String xx =null;

    public tcp_send(InetAddress ip, int post) {
        this.ip = ip;
        this.post = post;
    }

    public tcp_send(InetAddress ip, int post, String xx) {
        this.ip = ip;
        this.post = post;
        this.xx = xx;
    }

    @Override
    public void run() {
        try {

            //1.创建tcp协议的socket套接字
            socket = new Socket(ip, post);//指定连接的IP和端口
            System.out.println("连接成果");
            //2.创建TCP协议的发送类outputStream
            outputStream = socket.getOutputStream();//创建发流
            System.out.println("发送流创建成功");
            //3.获取命令行窗口的内容

            System.out.println("等待取出命令行中的内容");
//            System.out.println(buff.readLine());//获取文本行的内容
            //4.发送信息
            outputStream.write(xx.getBytes());
            System.out.println("已发送");


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
